var register = {
	init : function( ){
		$.getScriptSafe('/static/settings.js', register.loadMlPack);
	},
	
	loadMlPack : function(){
		$.getScriptSafe('/static/js/lib/ml-utils.js', register.loadScript1);
	},
	
	loadScript1 : function(){
		$.getScriptSafe('/static/js/thrird/jquery.maskedinput-1.3.min.js', register.allLoadsComplete);
	},

	allLoadsComplete: function () {
		
		$.each($('.content li select'), function (i, el) {
			var sel = $(el);
			sel.bind('change', function (e) {
				sel.prev().text(sel.find('option:selected').text());
			})
			.fadeTo(0,0)
			.css({visibility: 'visible'})
			.prev().text(sel.find('option:selected').text());
		})
		

		$('.birth-date input').mask("99/99/9999");
		$('.cpf input').mask("999.999.999-**");
		
		$('.cep input:eq(0)')
			.attr('maxlength', '5')
			.bind('keyup', register.onlyNumbers )
			.bind('keyup', function(e){
				if(e.currentTarget.value.length >= 5) $('.cep input:eq(1)').focus();
			});
		
		$('.cep input:eq(1)')
			.attr('maxlength', '3')
			.bind('keyup', register.onlyNumbers );

		$('.bt-fill').bind('click', register.mountAddress);
		$('.pagination a').bind('click', register.postForm );
		
		$('input#id_nickname').parent().parent().append( $('<input/>').attr({
			type: 'hidden',
			id: 'id_nickname_valid',
			value: '0'
		}));

		$('input#id_nickname')
			.bind('keyup'	, register.checkUsername.handleEvent )
			.bind('blur'	, register.checkUsername.handleEvent )
			.trigger('blur');
	},
	
	postForm: function(e){
		e.preventDefault();
		
		var isValid = true;
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_name').val() == ''){
			$('input#id_name').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_name').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_nickname').val() == '' || $('input#id_nickname_valid').val() == '0'){
			$('input#id_nickname').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_nickname').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if(!register.validateCPF($('input#id_cpf').val())){
			$('input#id_cpf').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_cpf').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_birth_date').val() == ''){
			$('input#id_birth_date').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_birth_date').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_zip1').val() == ''){
			$('input#id_zip1').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_zip1').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_zip2').val() == ''){
			$('input#id_zip2').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_zip2').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_address').val() == ''){
			$('input#id_address').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_address').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_address_number').val() == ''){
			$('input#id_address_number').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_address_number').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_city').val() == ''){
			$('input#id_city').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_city').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_neighborhood').val() == ''){
			$('input#id_neighborhood').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_neighborhood').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_area_code_home').val() == ''){
			$('input#id_area_code_home').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_area_code_home').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_home_phone').val() == ''){
			$('input#id_home_phone').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_home_phone').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_area_code_mobile').val() == ''){
			$('input#id_area_code_mobile').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_area_code_mobile').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_home_mobile').val() == ''){
			$('input#id_home_mobile').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_home_mobile').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;		
		if(!filter.test($('input#id_email').val())){
			$('input#id_email').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_email').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_password').val().length < 6){
			$('input#id_password').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_password').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if($('input#id_check_password').val() != $('input#id_password').val()){
			$('input#id_check_password').parent().parent().find('.input').addClass('error');
			isValid = false;
		}else{
			$('input#id_check_password').parent().parent().find('.input').removeClass('error');
		}
		//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

		if(isValid){
			$('form').submit();
		}else{
			$('html, body').animate({
				scrollTop: $('.input.error:eq(0)').offset().top - 50
			}, {
            duration: 800,
            queue: false
        });


			return; 
		}
	},
	
	getElAlert: function(attribute){
		return $('<p/>')
			.addClass('alert')
			.append($('<span/>').addClass('text'))
			.append($('<span/>').addClass('tl'	))
			.append($('<span/>').addClass('tr'	))
			.append($('<span/>').addClass('bl'	))
			.append($('<span/>').addClass('br'	));
	},
	
	validateCPF: function(data){
		var cpf = data.toString().replace(/\./g, '').replace(/\-/g, '');

		if (cpf.length != 11 || 
			cpf == "00000000000" || 
			cpf == "11111111111" || 
			cpf == "22222222222" || 
			cpf == "33333333333" || 
			cpf == "44444444444" || 
			cpf == "55555555555" || 
			cpf == "66666666666" || 
			cpf == "77777777777" || 
			cpf == "88888888888" || 
			cpf == "99999999999") return false;
		
		var add = 0;
		for (var i = 0; i < 9; i++) add += parseInt(cpf.charAt(i)) * (10 - i);
		
		var rev = 11 - (add % 11);
		if (rev == 10 || rev == 11) rev = 0;
		if (rev != parseInt(cpf.charAt(9))) return false;
		
		add = 0;
		
		for (i = 0; i < 10; i ++) add += parseInt(cpf.charAt(i)) * (11 - i);
		
		rev = 11 - (add % 11);
		if (rev == 10 || rev == 11) rev = 0;
		if (rev != parseInt(cpf.charAt(10))) return false;
		
		return true;
	},
	
	mountAddress: function(e){
		e.preventDefault();
		
		var cep = $('.cep input:eq(0)').val() + $('.cep input:eq(1)').val();
		
		if(cep.length < 8 ){
			alert('CEP inválido');
			return;
		};

		$.ajax({
			type: 'get',
			dataType: 'jsonp',
			jsonp: '?',
			jsonpCallback: 'fn',
			url: settings.user.addressFetch.format(cep),
			success: function(e){
				var fullAddress = arguments[0].payload;
				$('li.neighborhood input').val( fullAddress['@bairro'] );
				$('li.address input').val( fullAddress['@logradouro'] );
				$('li.city input').val( fullAddress['@localidade'] );
				$('li.state select option[selected]').removeAttr('selected');
				$('li.state select option[value="{0}"]'.format(fullAddress['@estado'].toUpperCase())).attr('selected', 'selected');
				$('li.state select').trigger('change');
				$('li.number input').focus();
			}
		});
	},
	
	checkUsername:{
		handleTimeout: null,
		alertTimeout: null,
		
		handleEvent: function(e){
			$('.user .status').addClass('loading');
			clearTimeout(register.checkUsername.handleTimeout);

			if(e.type == 'blur'){
				register.checkUsername.step2(e);
			}else{
				register.checkUsername.handleTimeout = setTimeout(register.checkUsername.step2, 2000, e);
			};
		},
		
		step2: function(e){
			var username = e.currentTarget.value;
			$.ajax({
				type: 'post',
				dataType: 'json',
				contentType: 'application/json',
				processData: false,
				data: new mlSerializer().add('login', username).render(),
				url: settings.user.loginFetch,
				success: register.checkUsername.step3
			});
		},
		
		step3: function(data, xhr, stt){
			if(data.success){
				$('.user .status').removeClass('loading').removeClass('error').addClass('success');
				$('input#id_nickname_valid').val('1');
				register.checkUsername.manageAlert(false);
			}else{
				$('.user .status').removeClass('loading').removeClass('success').addClass('error');
				$('input#id_nickname_valid').val('0');
				register.checkUsername.manageAlert(true, data.message.login);
			}
		},
		
		manageAlert: function(show, message){
			var alert = $('.user .alert').length == 0 ? register.getElAlert().appendTo( $('.user') ).hide() : $('.user .alert');
			
			if(show){
				alert.show().find('.text').html(message);
			}else{
				alert.hide();
			}
		},
	},
	
	onlyNumbers : function(e){
		var v = e.currentTarget.value;
		v = v.replace(/\D/g, ""); 
		e.currentTarget.value = v;
	}
};

$(document).ready(register.init);